package jk.spider.core.storage.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import jk.spider.core.storage.ImgInfoDAO;
import jk.spider.model.ImgInfo;

public class ImgInfoDAOImpl implements ImgInfoDAO {
	protected static final Logger log = Logger.getLogger(ImgInfoDAOImpl.class);
	protected DAOHelp daoHelp;

	public ImgInfoDAOImpl(DAOHelp daoHelp) {
		this.daoHelp = daoHelp;
	}
	
	public ImgInfo findById(int rid) {
		String sql = "select rid, imgUrl, imgTitle, imgType from spider_resource_imgInfo where rid = " + rid;
		ResultSet rs = null;
		Statement stmt = null;
		ImgInfo imgInfo = new ImgInfo();
		try {
			stmt = daoHelp.getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				imgInfo.setRid(rs.getInt(1));
				imgInfo.setImgUrl(rs.getString(2));
				imgInfo.setImgTitle(rs.getString(3));
				imgInfo.setImgType(rs.getString(4));
			}
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} catch (SQLException e) {
			log.error("SQLException -> ", e);
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} finally {
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		}
		return imgInfo;
	}

	public void create(ImgInfo info) {
		StringBuffer sql = new StringBuffer();
		sql.append("insert into spider_resource_imgInfo (rid, imgUrl, imgTitle, imgType )");
		sql.append( " values ( ");
		sql.append(daoHelp.format(info.getRid()) + ",");
		sql.append(daoHelp.format(info.getImgUrl()) + ",");
		sql.append(daoHelp.format(info.getImgTitle()) + ",");
		sql.append(daoHelp.format(info.getImgType()) + ")");
		daoHelp.execSql(sql.toString());
	}
}
